<!--
 * @Description: 下拉CheckBox
 * @Author: seadon
 * @LastEditors: seadon
 * @Date: 2021-07-09 14:22:17
 * @LastEditTime: 2021-11-16 20:57:56
-->
<template>
	<div
		class="drop-checkbox drop-checkbox-new"
		:class="{
			'drop-checkbox-layout': !isChangeLayout,
			'drop-checkbox-agent': !isChangeLayout && isAgentCheck,
		}"
	>
		<a-select
			v-if="isChangeLayout || isAgentCheck"
			:tagRender="renderSelectTag"
			v-model:value="dataRef"
			:maxTagCount="1"
			:placeholder="placeholder"
			mode="tags"
			style="width: 220px"
			class="pok-drop-checkbox"
			dropdownClassName="pok-drop-checkbox-content"
			:dropdownMatchSelectWidth="false"
			@dropdownVisibleChange="handleBlurSelect"
			@change="handleChangeChecked"
			:menuItemSelectedIcon="getIcons"
		>
			<!-- <template #suffixIcon><span class="low-code iconpackup"></span></template> -->
			<template
				#dropdownRender="{ menuNode: menu }"
				v-if="checkTotal && checkOptions.length"
			>
				<div
					class="item-check"
					:class="{ 'all-check': allChecked }"
					@mousedown="e => e.preventDefault()"
					@click="handleCheckAll"
				>
					<span class="check-icon">
						<i class="low-code icona-duoxuanxuanzhong" v-if="allChecked"></i>
						<i
							class="low-code iconduoxuan-bufenxuanze"
							v-else-if="partChecked"
						></i>
						<i class="low-code icona-duoxuanweixuanzhong" v-else></i>
					</span>
					<span class="check-text">{{ checkTotal.text }}</span>
					<span class="check-count">{{ checkTotal.count }}</span>
				</div>
				<a-divider style="margin: 4px 0" />
				<v-nodes :vnodes="menu" />
			</template>
			<a-select-option
				v-for="item in checkOptions"
				:key="item?.value"
				:value="item?.value"
			>
				<div class="option-item">
					<div class="item-title">
						<ok-person-cell
							class="item-title-person"
							v-if="item.user"
							width="18px"
							height="18px"
							.person-info="item.user"
						></ok-person-cell>
						<EllipsisTooltip style="max-width: 84%" :title="item?.text" />
					</div>
					<div class="item-count">{{ item?.count }}</div>
				</div>
			</a-select-option>
		</a-select>
		<div v-else class="left-layout">
			<!-- 流程类别 流程筛选 -->
			<a-select
				v-model:value="selectFilter"
				@change="changeChecked"
				v-if="taskType === taskTypeEnum.TodoTask"
			>
				<a-select-option :value="false">{{
					$t('delegate.unfiller', '显示委托待办')
				}}</a-select-option>
				<a-select-option :value="true">{{
					$t('delegate.filler', '过滤委托待办')
				}}</a-select-option>
			</a-select>
			<div
				v-if="!isAgentCheck"
				class="filter-list"
				:class="{
					'filter-list-layout': !isChangeLayout,
					'filter-list-box': !isChangeLayout && taskType === 'DoneTask',
				}"
			>
				<a-checkbox
					a-checkbox
					v-model:checked="typeCheckAll"
					:indeterminate="indeterminate"
					@change="onCheckAllChange"
				>
					<div class="check-text">{{ checkTotal.text }}</div>
					<div class="check-count">{{ checkTotal.count }}</div>
				</a-checkbox>
				<a-checkbox-group
					v-model:value="dataRef"
					class="checkbox-item"
					@change="CheckboxGroupChange"
				>
					<template v-for="item in checkOptions" :key="item.text">
						<a-checkbox :value="item.value" @change="onCheckChange">
							<div class="check-item">
								<div class="check-item-title">
									<ok-person-cell
										class="check-item-title-person"
										v-if="item.user"
										width="18px"
										height="18px"
										.person-info="item.user"
									></ok-person-cell>
									<EllipsisTooltip class="check-text" :title="item?.text" />
								</div>
								<div class="check-item-count">{{ item?.count }}</div>
							</div>
						</a-checkbox>
					</template>
				</a-checkbox-group>
			</div>
		</div>
	</div>
</template>

<!-- <script>
export default {
	name: 'DropCheckbox',
	inheritAttrs: false,
}
</script> -->
<script setup lang="ts">
import {
	ref,
	defineProps,
	computed,
	unref,
	watchEffect,
	h,
	defineEmits,
	watch,
	onMounted,
	nextTick,
} from 'vue'
import type { Ref } from 'vue'
import { cloneDeep, remove } from 'lodash'
import { createFromIconfontCN } from '@ant-design/icons-vue'
import EllipsisTooltip from '@/entry_desktop/components/EllipsisTooltip'
import { taskTypeEnum, doneTaskEnum } from '@/constant/enums/processCenter'
import { i18n } from '@/locales'
import './index.less'
import { useStore } from 'vuex'
const { $t: iTrans } = i18n

const MyIcon = createFromIconfontCN({
	scriptUrl: '//at.alicdn.com/t/font_2720651_t87dwgc3qo.js',
})
const store = useStore()
const props = defineProps<{
	tagRender: string
	checkData?: string[]
	checkOptions?: Recordable<any>[]
	checkTotal?: Recordable<any>
	placeholder?: string
	isChangeLayout: boolean
	taskType: keyof typeof taskTypeEnum
	isAgentCheck: boolean
	resetCheckVal: any
	filterChecked: boolean
	doneType: string
}>()
const emit = defineEmits(['onBlur', 'getCheckData', 'changeChecked'])
const VNodes = (_: any, { attrs }: any) => {
	return attrs.vnodes
}
let prevData: string[] | undefined = []
const dataRef: Ref<string[] | undefined> = ref([''])
const tagRef = ref(props.tagRender)
const propCheckData = computed(() => props.checkData)
const selectFilter = ref(props.filterChecked)
const allChecked = computed(() => {
	tagRef.value =
		unref(dataRef)?.length === props.checkOptions?.length
			? props.tagRender
			: iTrans('component.state.checked', `已选 ${unref(dataRef)?.length} 项`, {
					count: unref(dataRef)?.length || 0,
			  })
	return (
		unref(dataRef)?.length &&
		unref(dataRef)?.length === props.checkOptions?.length &&
		props.checkOptions?.length
	)
})
const partChecked = computed(() => {
	const checkDatas = unref(dataRef)
	return (
		!unref(allChecked) &&
		checkDatas?.length &&
		(checkDatas?.length !== 1 ||
			(checkDatas?.length === 1 && String(checkDatas) !== ''))
	)
})
watchEffect(() => {
	dataRef.value = props.checkData
})

const handleChangeChecked = () => {
	const checkDatas = [...(unref(dataRef) as string[])]
	remove(checkDatas, function (v) {
		return v === ''
	})
	const count = checkDatas.length
	tagRef.value =
		unref(allChecked) || !count
			? props.tagRender
			: iTrans('component.state.checked', `已选 ${count} 项`, { count })
}

const handleCheckAll = () => {
	if (!unref(allChecked)) {
		dataRef.value = props.checkOptions?.map(item => item.value)
	} else {
		dataRef.value = []
	}
	handleChangeChecked()
}

const handleBlurSelect = (open: any) => {
	const isFirst =
		unref(propCheckData)?.length === unref(allChecked) &&
		!prevData?.length &&
		props.checkOptions?.length == unref(dataRef)?.length
	if (open || isFirst) return
	if (unref(propCheckData)?.length !== prevData?.length) {
		prevData = cloneDeep(unref(propCheckData))
	}
	if (
		prevData?.sort().toString() !== unref(dataRef)?.sort().toString() ||
		!unref(dataRef)?.length
	) {
		emit('onBlur', unref(dataRef))
		prevData = cloneDeep(unref(dataRef))
	}
}

const getIcons = ({ isSelected }: { isSelected: boolean }) => {
	if (isSelected) {
		return h(MyIcon, { type: 'icon-checked' })
	}
	return h(MyIcon, { type: 'icon-check-no' })
}

const selectEl = computed(() => {
	return h('span', { class: 'select-custom-item' }, [
		h('span', { class: 'select-custom-item-content' }, unref(tagRef.value)),
		h('i', { class: 'low-code iconpackup arrow-icon' }),
	])
})
const renderSelectTag = () => {
	return selectEl.value
}
//流程中心左右布局 筛选
const typeCheckAll = ref(true)
const indeterminate = ref(true)
const onCheckAllChange = (e?: any) => {
	let list: any
	if (!e) {
		if (props.taskType === 'DoneTask') {
			if (store.state.firterAfterDate['DoneTask'][props.doneType]) {
				list = store.state.firterAfterDate['DoneTask'][props.doneType]
			} else {
				list = props.checkOptions?.map((item: any) => item.value)
			}
		} else {
			if (store.state.firterAfterDate[props.taskType]) {
				list = store.state.firterAfterDate[props.taskType]
			} else {
				list = props.checkOptions?.map((item: any) => item.value)
			}
		}
	} else {
		list = e.target.checked
			? props.checkOptions?.map((item: any) => item.value)
			: []
		store.commit('setFirterAfterDate', {
			checkedValue: e.target.checked
				? props.checkOptions?.map((item: any) => item.value)
				: [],
			taskType: props.taskType,
			doneType: props.doneType,
		})
	}
	dataRef.value = e ? (e?.target.checked ? list : []) : list
	typeCheckAll.value = e?.target.checked
	indeterminate.value = true
	emit('getCheckData', dataRef.value)
}

const onCheckChange = (e: any) => {
	nextTick(() => {
		emit('getCheckData', dataRef.value)
	})
}

const changeChecked = (value: boolean) => {
	emit('changeChecked', value)
}
//存储修改后的值（存入vuex）
const CheckboxGroupChange = (checkedValue: any) => {
	store.commit('setFirterAfterDate', {
		checkedValue: checkedValue,
		taskType: props.taskType,
		doneType: props.doneType,
	})
}
watch(
	() => dataRef.value,
	(val: any) => {
		indeterminate.value = !!val.length && val.length < props.checkOptions.length
		typeCheckAll.value = val.length === props.checkOptions.length
	}
)
watch(
	() => props.resetCheckVal[0],
	(newVal, oldVal) => {
		dataRef.value = props.checkOptions?.map((item: any) => item.value)
	},
	{ immediate: true, deep: true }
)
watch(
	() => typeCheckAll.value,
	(val: any) => {
		const list: any = props.checkOptions?.map((item: any) => item.value)
		dataRef.value = val ? list : dataRef.value
	}
)
watch(
	() => props.filterChecked,
	(newVal, oldVal) => {
		selectFilter.value = unref(newVal)
	}
)
onMounted(() => {
	onCheckAllChange()
})
</script>
<style lang="less">
.pok-drop-checkbox {
	.ant-select-selection-search {
		display: none;
		cursor: pointer;
	}
}
.ant-select-show-search.ant-select-multiple .ant-select-selector {
	cursor: pointer;
	.ant-select-selection-overflow-item > span {
		pointer-events: none;
	}
}
.iconduoxuan-bufenxuanze {
	color: @rok-primary-color;
}
.icon-a-duoxuanweixuanzhong {
	color: @rok-auxiliary-color;
}
.left-layout {
	height: 100%;
	display: flex;
	flex-direction: column;
	.ant-select {
		margin-right: 14px;
		margin-bottom: 10px;
	}
	.filter-box {
		.filter-box-top {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 16px;
			.filter-title {
				font-size: 14px;
				font-weight: 500;
				color: #1f2329;
			}
			.filter-btn {
				.ant-btn {
					font-weight: 500;
					font-size: 12px;
					color: rgba(0, 0, 0, 0.85);
				}
				.ant-btn-primary {
					color: #fff;
					margin-right: 8px;
				}
			}
		}
	}
	.filter-list {
		// min-width: 280px;
		// max-width: 350px;
	}
	.filter-list > label {
		display: flex;
		align-items: center;
		span:first-child {
			margin-bottom: 5px;
		}
		span:last-child {
			display: flex;
			justify-content: space-between;
		}
	}
	.line {
		height: 1px;
		width: 30px;
		color: #e8eaed;
	}
	.ant-select-selection-item {
		display: block !important;
	}
}

.drop-checkbox-new {
	.ant-checkbox-group {
		width: 100%;
	}
	.ant-checkbox + span {
		width: 94%;
	}
	.ant-checkbox-group > label {
		display: flex;
		align-items: center;
		span:first-child {
			margin-bottom: 5px;
		}
	}
	.ant-checkbox-group > label span:last-child {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}
	.ant-checkbox-wrapper + .ant-checkbox-wrapper {
		margin-left: 0;
	}
	.drop-checkbox-layout {
		display: flex;
		flex-direction: column;
	}
	.filter-list-layout {
		overflow-y: auto;
		height: 100%;
	}
	.filter-list-box {
		overflow-y: auto;
		height: 95%;
	}
	.filter-agent-layout {
		overflow-y: auto;
		height: 100%;
	}
	.check-item {
		width: 100%;
		display: flex;
		justify-content: space-between;
		.check-item-title {
			min-width: 207px;
			flex: 1;
			overflow: hidden;
			display: flex;
			align-items: center;
			.check-item-title-person {
				margin-right: 4px;
			}
		}

		.check-item-count {
			width: 35px;
			text-align: right;
		}
	}
	.left-agent-check {
		.ant-checkbox-wrapper {
			display: flex;
			align-items: center;
		}
		.ant-checkbox-wrapper span:last-child {
			.check-item-title {
				display: flex;
				align-items: center;
				justify-content: space-between;
			}
		}
		.ant-radio-group {
			width: 100%;
		}
		.ant-radio-wrapper {
			display: flex;
			align-items: center;
			height: 32px;
			margin: 0;
			> span:last-child {
				display: flex;
				width: 100%;
			}
		}
	}
	span.ant-radio + * {
		padding-right: 20px;
	}
	label.ant-radio-wrapper:hover {
		background: #f5f6f7;
	}
	.ant-checkbox-wrapper {
		height: 32px;
	}
	.ant-checkbox-wrapper:hover {
		background: #f5f6f7;
	}
	label.ant-radio-wrapper.ant-radio-wrapper-checked,
	.ant-checkbox-wrapper.ant-checkbox-wrapper-checked {
		color: #4c78fc;
	}
	.checkbox-item {
		.check-text {
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}
	}
	.ant-select-selector > span:nth-child(2),
	.ant-select-selection-overflow-item > span:nth-child(2) {
		display: none;
	}
	.ant-select-selection-overflow-item-rest {
		display: none;
	}
	.pok-drop-checkbox {
		position: relative;
		// vertical-align: text-top;
		.select-custom-item {
			.arrow-icon {
				position: absolute;
				right: 8px;
			}
		}
	}
}
.drop-checkbox-agent {
	position: absolute;
	top: 81px;
	left: 321px;
}
</style>
